﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NewsClassifierFreshnessMeasurement.Crawl;
using NCTrainingDataScraper;
using System.Web;
using System.IO;
using System.Reflection;

namespace WebClass
{
    public class CoverageOperation
    {
        public static string GetPosition(int position)
        {
            if (position > 0 && position < 3)
            {
                return "T";
            }
            else if (position >= 3 && position <= 8)
            {
                return "M";
            }
            else if (position >= 9)
            {
                return "B";
            }
            else if (position == -1)
            {
                return "NT";//not found in ping result
            }
            else
            {
                return "";//not ping bing
            }
            
        }
        public int GetPosition(int taskID, int newsID, string query)
        {
            var queryRes = from e in researchDB.tb_experiments
                           from q in e.tb_experimentsQueries
                           where e.taskID == taskID && e.newsID == newsID && q.query == query
                           select q;
            if (queryRes.Count() > 0)
            {
                return (int)(queryRes.First().position);
            }
            return -2;
        }
        ResearchDBDataContext researchDB = new ResearchDBDataContext();
        private string GetMarket(int newsID)
        {
            var res = from n in researchDB.tb_news
                      where n.ID == newsID
                      select new
                      {
                          market = n.market
                      };
            if (res.Count() > 0)
            {
                return res.First().market;
            }
            return "";
        }
        public string EncodeUrl(string query,int newsID)
        {
            string market = GetMarket(newsID);
            string url = "";
            if (market.ToLower() == "en-us")
            {
                url = "http://origin.co3.bing.com/search?q=" + HttpUtility.UrlEncode(query) + "&form=MONITR&mkt=en-us&setflight=flt9:0&setflight=flt3:0&setflight=flt23:0";
            }
            else if (market.ToLower() == "zh-cn")
            {
                url = "http://origin.bj1.bing.com/search?q=" + HttpUtility.UrlEncode(query) + "&form=MONITR&mkt=zh-cn&setflight=flt9:0&setflight=flt3:0&setflight=flt23:0";
            }
            return url;
        }
        public int Crawler(string query,int newsID)
        {
            Crawler crawler = NewsClassifierFreshnessMeasurement.Crawl.Crawler.CreateCrawler(CrawlerType.Net);
            var result = crawler.Crawl(new CrawlerParam
            {
                Uri = EncodeUrl(query,newsID),
                Proxy = "itgproxy.redmond.corp.microsoft.com",
                UserAgent = CrawlerParam.UserAgent_IE9,
                Timeout = 10000
            });

            ResponseParser parser = ResponseParser.CreateResponseParser(ParserType.Bing);
            NewsAnswerPositionInfo newsAnswerInfo = parser.Parse(result.Content);
            if (newsAnswerInfo != null)
            {
                return newsAnswerInfo.AnswerPosition;
            }
            return -1;
        }
        public void TriggerEvent(int taskID)
        {
            AddTaskIDQueue(taskID);
            string path = HttpContext.Current.Server.MapPath(".") + @"\flag.txt";

            FileStream fs = new FileStream(path, FileMode.Truncate);
            StreamWriter w = new StreamWriter(fs);
            w.Write(path);
            w.Close();
            fs.Close();
        }
        public void AddTaskIDQueue(int _taskID)
        {
            if (!IsTaskInQueue(_taskID))
            {
                tb_taskIDQueue taskIDQueue = new tb_taskIDQueue
                {
                    taskID = _taskID
                };
                researchDB.tb_taskIDQueues.InsertOnSubmit(taskIDQueue);
                researchDB.SubmitChanges();
            }
        }
        public void DeleteTaskIDInQueue(int _taskID)
        {
            var taskIDRes = from t in researchDB.tb_taskIDQueues
                            where t.taskID == _taskID
                            select t;
            if (taskIDRes.Count() > 0)
            {
                foreach(var item in taskIDRes)
                    researchDB.tb_taskIDQueues.DeleteOnSubmit(item);
                researchDB.SubmitChanges();
            }
        }
        public bool IsTaskInQueue(int _taskID)
        {
            var taskIDRes = from t in researchDB.tb_taskIDQueues
                            where t.taskID == _taskID
                            select t;
            if (taskIDRes.Count() > 0)
            {
                return true;
            }
            return false;
        }
        public bool IsPingBingComplete(int _taskID)
        {
            var queryRes = from e in researchDB.tb_experiments
                            from q in e.tb_experimentsQueries
                            where e.taskID == _taskID && q.position == -2
                            select q;
            if (queryRes.Count() > 0)
            {
                return false;
            }
            return true;
        }
    }
}
